package tech.aistar.design.singleton;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * 本类用来演示: 防止序列化/反射技术来破坏
 *
 * 最优雅的方式 - 饿汉 - 多线程安全的
 *
 * @author: success
 * @date: 2022/7/27 10:57 上午
 */
public enum Singleton05 {
    INSTANCE;

    Singleton05(){
        System.out.println("进行初始化的操作...");
    }

    //public void test(){
    //
    //}
}
class Singleton05Test{
    public static void main(String[] args) {
        Singleton05 s1 = Singleton05.INSTANCE;
        Singleton05 s2 = Singleton05.INSTANCE;
        System.out.println(s1 == s2);

        //获取class实例
        Class<?> c = Singleton04.class;

        Class<?> c2 = Singleton05.class;

        //访问私有的

        //反射调用构造方法
        try {
            Constructor<?> constructor = c.getDeclaredConstructor();

            //测试枚举 - 禁止获取构造
            Constructor<?> constructor2 = c2.getDeclaredConstructor();
            constructor2.setAccessible(true);

            //java.lang.NoSuchMethodException: tech.aistar.design.singleton.Singleton05.<init>()
            Singleton05 s5 = (Singleton05) constructor2.newInstance();



            //反射破坏封装性
            constructor.setAccessible(true);

            Singleton04 s3 = (Singleton04) constructor.newInstance();
            Singleton04 s4 = (Singleton04) constructor.newInstance();

            System.out.println(s3 == s4);//false => 反射技术破坏单例性




        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
